package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.HomeBannerBean;
import com.android.infantschool.event.HomeBannerEvent;
import com.android.infantschool.manager.ActManager;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.mvp.presenter.HomeBannerPresenter;
import com.android.infantschool.model.mvp.presenter.HomeBannerPresenterImpl;
import com.android.infantschool.model.mvp.view.HomeBannerView;
import com.android.infantschool.service.InfantService;
import com.android.infantschool.ui.fragment.ClockingFragment;
import com.android.infantschool.ui.fragment.DynamicFragment;
import com.android.infantschool.ui.fragment.HomeFragment;
import com.android.infantschool.ui.fragment.InfromFragment;
import com.android.infantschool.ui.fragment.MeFragment;
import com.android.infantschool.util.StatusBarUtil;
import com.android.infantschool.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener, HomeBannerView {

    private static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.main_tab_home)
    public RadioButton mainTabHome;
    @BindView(R.id.main_tab_clocking)
    public RadioButton mainTabClocking;
    @BindView(R.id.main_tab_dynamic)
    public RadioButton mainTabDynamic;
    @BindView(R.id.main_tab_inform)
    public RadioButton mainTabInform;
    @BindView(R.id.main_tab_me)
    public RadioButton mainTabMe;

    @BindView(R.id.main_table)
    public RadioGroup mainTable;

    public static Intent newIntent(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        return intent;
    }

    private HomeFragment homeFragment;
    private ClockingFragment clockingFragment;
    private DynamicFragment dynamicFragment;
    private InfromFragment infromFragment;
    private MeFragment meFragment;

    public static volatile MainActivity Instance = null;
    private HomeBannerPresenter homeBannerPresenter;

    private FragmentManager manager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
        //setStatusBar();
        setContentView(R.layout.activity_main);
        Instance = this;
        ActManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initView();
        JPushInterface.setAlias(this, Integer.parseInt(AppConfig.getUserPhone().substring(AppConfig.getUserPhone().length() - 6, AppConfig.getUserPhone().length())), AppConfig.getUserPhone());
        startService(new Intent(this, InfantService.class));
    }

    private void initView() {
        homeBannerPresenter = new HomeBannerPresenterImpl(this);

        /**
         * 获取首页轮播图
         */
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("role", "1");
        homeBannerPresenter.getHomeBanner(map);


        mainTable.setOnCheckedChangeListener(this);
        mainTabHome.setChecked(true);
        mainTabClocking.setChecked(false);
        mainTabDynamic.setChecked(false);
        mainTabInform.setChecked(false);
        mainTabMe.setChecked(false);
    }

    protected void setStatusBar() {
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, true);
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        selectTab(checkedId);
    }

    //进行选中Tab的处理
    private void selectTab(int id) {
        //获取FragmentManager对象
        if (manager == null) {
            manager = getSupportFragmentManager();
        }
        FragmentTransaction transaction = manager.beginTransaction();
        //先隐藏所有的Fragment
        hideFragments(transaction);
        switch (id) {
            case R.id.main_tab_home://首页
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.main_fragment, homeFragment);
                } else {
                    //如果对应的Fragment已经实例化，则直接显示出来
                    transaction.show(homeFragment);
                }
                break;
            case R.id.main_tab_clocking://考勤
                if (clockingFragment == null) {
                    clockingFragment = new ClockingFragment();
                    transaction.add(R.id.main_fragment, clockingFragment);
                } else {
                    transaction.show(clockingFragment);
                }
                break;
            case R.id.main_tab_dynamic://动态
                if (dynamicFragment == null) {
                    dynamicFragment = new DynamicFragment();
                    transaction.add(R.id.main_fragment, dynamicFragment);
                } else {
                    transaction.show(dynamicFragment);
                }
                break;
            case R.id.main_tab_inform://通知
                if (infromFragment == null) {
                    infromFragment = new InfromFragment();
                    transaction.add(R.id.main_fragment, infromFragment);
                } else {
                    transaction.show(infromFragment);
                }
                break;
            case R.id.main_tab_me://我的
                if (meFragment == null) {
                    meFragment = new MeFragment();
                    transaction.add(R.id.main_fragment, meFragment);
                } else {
                    transaction.show(meFragment);
                }
                break;
        }
        //不要忘记提交事务
        transaction.commit();
    }

    //将四个的Fragment隐藏
    private void hideFragments(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (clockingFragment != null) {
            transaction.hide(clockingFragment);
        }
        if (dynamicFragment != null) {
            transaction.hide(dynamicFragment);
        }
        if (infromFragment != null) {
            transaction.hide(infromFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            } else {
                ActManager.getAppManager().AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JPushInterface.deleteAlias(this, Integer.parseInt(AppConfig.getUserPhone().substring(AppConfig.getUserPhone().length() - 6, AppConfig.getUserPhone().length())));
        if (homeBannerPresenter != null) {
            homeBannerPresenter.onDestroy();
            homeBannerPresenter = null;
        }
    }

    /**
     * 重置App界面的字体大小，fontScale 值为 1 代表默认字体大小
     *
     * @return suyan
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = res.getConfiguration();
        config.fontScale = 1;
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    public void errorHomeBanner(String error) {
        Log.e(TAG, "请求出错:" + error);
    }

    @Override
    public void successHomeBanner(BaseBean baseBean) {
        HomeBannerBean homeBannerBean = (HomeBannerBean) baseBean;
        Log.e(TAG, "请求成功:" + homeBannerBean.toString());
        if (homeBannerBean.getCode().equals("0") || homeBannerBean.getData() != null) {
            if (homeBannerBean.getData().size() > 0) {
                List<Object> list = new ArrayList<>();
                for (int index = 0; index < homeBannerBean.getData().size(); index++) {
                    list.add(homeBannerBean.getData().get(index));
                }
                EventBus.getDefault().post(new HomeBannerEvent(1, list));
            }
        }
    }
}